package routefinder.loader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import routefinder.City;
import routefinder.IRoutesMap;
import routefinder.exception.RouteFinderException;

/**
 * Loads edges of the graph that is defined in the below format:
 * AB5,CD3
 *
 * The 1st position is the starting city.
 * The 2nd position is the destination city.
 * The distance between those cities
 *  A comma
 *
 * @author luky
 */
public class DefaultDataLoader implements IDataLoader {

    public static final String ERROR_MSG_CLOSING_STREAM = "Error trying to close inputstream";
    public static final String IO_ERROR_READING_STREAM = "Error trying to read inputstream: ";
    private static final Logger LOG = Logger.getLogger(DefaultDataLoader.class.getName());

    public void loadIntoMemory(final InputStream is, final IRoutesMap map) {
        try {
            final BufferedReader bf = new BufferedReader(new InputStreamReader(is));
            LOG.info("Loading graph...");
            String s = null;
            while (true) {
                s = bf.readLine();
                if (s == null) {
                    break;
                }
                StringTokenizer st = new StringTokenizer(s, ","); //TODO bug when theres only 1 route. ex: AB5
                while (st.hasMoreElements()) {
                    String city1City2Distance = ((String)st.nextElement()).trim();
                    City origin = new City(city1City2Distance.substring(0, 1));
                    City destination = new City(city1City2Distance.substring(1, 2));
                    int distance = Integer.parseInt(city1City2Distance.substring(2));
                    map.addDirectRoute(origin,destination,distance);
                }
            }
        } catch (IOException io) {
            throw new RouteFinderException(IO_ERROR_READING_STREAM, io);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                throw new RouteFinderException(ERROR_MSG_CLOSING_STREAM, ex);
            }
        }
    }
}
